home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 15361 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  53 lines

  1. Path: ub239.dialup.uwa.edu.au!localhost!prye
  2. From: prye@cyllene.uwa.edu.au (Peter Rye)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: casting a void pointer back to a function pointer
  5. Date: 04 Apr 1996 17:42:22 GMT
  6. Organization: The University of Western Australia
  7. Message-ID: <PRYE.96Apr5014222@cyllene.uwa.edu.au>
  8. References: <DLABELL.96Apr4021045@columbia.pcs.cnu.edu>
  9. NNTP-Posting-Host: ub239.dialup.uwa.edu.au
  10. In-reply-to: dlabell@pcs.cnu.edu's message of 04 Apr 1996 07:10:45 GMT
  11. X-Mailer: GNU Emacs 19.28
  12.  
  13. >>>>> "Daniel" == Daniel LaBell <dlabell@pcs.cnu.edu> writes:
  14.  
  15.     Daniel> get right to the problem.  How do I cast a pointer to a
  16.     Daniel> function pointer?
  17.  
  18.     Daniel> Here is trivial example that shows the problem.
  19.  
  20.     Daniel> void foo1(){ cout << " foo1 " << endl; } 
  21.     Daniel> void foo2(){ cout << " foo2 " << endl; } 
  22.     Daniel> void foo3(int x) { cout << " foo3, argument = " << x << endl; }
  23.  
  24.     Daniel> void do_a_foo( void (*fun)() ) { (*fun)(); } 
  25.     Daniel> void do_a_foo2(int x, void (*fun) (int )) { (*fun) ( x ); }
  26.  
  27.     Daniel> int main() { 
  28.     Daniel>    do_a_foo ( foo1 ); 
  29.     Daniel>    do_a_foo ( foo2 );
  30.     Daniel>    do_a_foo2 ( 2, foo3 ); 
  31.     Daniel>    void * x=foo2; 
  32.     Daniel>    do_a_foo (x); // I don't know the syntax to do this cast. :( 
  33.     Daniel>    return 0; } 
  34.  
  35. Actually you do know the syntax for the cast. You've written it out 
  36. in your function declarations. ;-) 
  37. Instead of making x a void*, declare it as a function pointer.
  38. ie:
  39.     void(*x)() = foo2;
  40.     or void(*x)(int) = foo3; for a pointer to foo3.
  41.  
  42. A typedef would make things less ugly.
  43. I'm sure this can be done in a much slicker object oriented C++ way.
  44.  
  45. ANSI C doesn't allow the implicit conversion between void * and pointer-to-
  46. function.
  47.  
  48. --
  49. Peter Rye   prye@cyllene.uwa.edu.au,  prye@ichr.uwa.edu.au
  50. Respiratory Research Fellow, Princess Margaret Hospital for Children
  51. Perth, Western Australia    Ph: +61 (09) 340 8985, Fax: +61 (09) 388 2097
  52. ** Smoking areas in restaurants are like peeing areas in swimming pools. **
  53.